﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using YiLe.DAL.Dao;
using YiLe.Model.Domain;
using NHibernate;
namespace YiLe.DAL.NHibernate
{
    public class MenuDaoHibernate:BaseHibernate<Menu, int>, MenuDao
    {
        public IDictionary<Menu, IList<Menu>> GetMenus(string loginName)
        {
            IList<Menu> mainMenus = HibernateTemplate.ExecuteFind<Menu>(
                delegate(ISession session) 
                {
                    return session.CreateSQLQuery("SELECT DISTINCT(p.MenuID), m.* FROM Users u, Users_Roles ur, Roles r, Roles_Permissions rp, Permissions p, Menu m WHERE u.LoginName=? AND m.ParentID = 0 AND u.UserID = ur.UserID AND ur.RoleID = r.RoleID AND r.RoleID = rp.RoleID AND rp.PermissionID = p.PermissionID AND p.MenuID = m.MenuID;").AddEntity("Menu", typeof(Menu)).SetParameter(0, loginName).List<Menu>();
                });

            IDictionary<Menu, IList<Menu>> menuDict = new Dictionary<Menu, IList<Menu>>();
            foreach (var menu in mainMenus)
            {
                IList<Menu> subMenus = HibernateTemplate.ExecuteFind<Menu>(
                    delegate(ISession session) 
                    {
                        return session.CreateSQLQuery("SELECT DISTINCT(p.MenuID), m.* FROM Users u, Users_Roles ur, Roles r, Roles_Permissions rp, Permissions p, Menu m WHERE u.LoginName=? AND m.ParentID = ? AND u.UserID = ur.UserID AND ur.RoleID = r.RoleID AND r.RoleID = rp.RoleID AND rp.PermissionID = p.PermissionID AND p.MenuID = m.MenuID;").AddEntity("Menu", typeof(Menu)).SetParameter(0, loginName).SetParameter(1, menu.MenuID).List<Menu>();

                    });
                menuDict.Add(menu, subMenus);
            }
            return menuDict;
        }

        public IList<Menu> GetSubMenu()
        {
            throw new NotImplementedException();
        }
    }
}
